package com.joint.web.action.com;

import com.fz.us.base.bean.BaseEnum;
import com.fz.us.base.bean.BaseEnum.StateEnum;
import com.fz.us.base.bean.Pager;
import com.joint.base.entity.FileManage;
import com.joint.base.util.DataUtil;
import com.joint.base.util.StringUtils;
import com.joint.core.entity.Client;
import com.joint.core.entity.Linkman;
import com.joint.core.entity.ProInfo;
import com.joint.core.service.ClientService;
import com.joint.core.service.LinkmanService;
import com.joint.core.service.ProInfoService;
import com.joint.web.action.BaseAdminAction;
import net.sf.json.JSONObject;
import org.apache.struts2.convention.annotation.ParentPackage;

import javax.annotation.Resource;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.*;

/**
 * Created by dqf on 2015/3/3.
 */
@ParentPackage("com")
public class AjaxLinkmanAction  extends BaseAdminAction {
    @Resource
    private ClientService clientService;
    @Resource
    private LinkmanService linkmanService;
    @Resource
    private ProInfoService proInfoService;

    protected Pager pager;

    private Linkman linkman;
    private String keyId;
    private String clientId;
    private Client client;
    private String name;
    private String subName;
    private String duty;
    private String tel;
    private String mobile;
    private String mobile_back;
    private String email;
    private String preferences;
    private String ifHasDecision;
    private Date birthday;
    private int birthdayMonth;
    private int birthdayDay;
    private String remark;
    protected List<Linkman> linkmanList;

    private FileManage fileManage;
    private String fileId;
    private String gridId;
    private File filedata;
    private String filename;
    private String fileUrl;

    public String list(){
        pager = new Pager();
        if (rows <= 0){
            rows = 10;
        }
        pager.setPageSize(rows);
        pager.setPageNumber(page);
        pager.setOrderBy("createDate");
        pager.setOrderType(BaseEnum.OrderType.desc);
        if(StringUtils.isNotEmpty(sidx)&&BaseEnum.OrderType.valueOf(sord)!=null){
            pager.setOrderBy(sidx);
            pager.setOrderType(BaseEnum.OrderType.valueOf(sord));
        }
        Map<String,Object> params = new HashMap<String,Object>();
        params.put("name", name);
        params = getSearchFilterParams(_search,params,filters);

        if (StringUtils.isNotEmpty(clientId)){
            client = clientService.get(clientId);
            params.put("client",client);
        }

        pager = linkmanService.findByPagerAndCompany(pager,null,usersService.getCompanyByUser(),params);

        linkmanList = (List<Linkman>) pager.getList();
        List<JSONObject> dataRows=new ArrayList<JSONObject>();
        Map<String, Object> data = new HashMap<String, Object>();
        Map<String,Object> rMap;
        for(Linkman linkman:linkmanList){
            rMap = new HashMap<String, Object>();
            rMap.put("id",linkman.getId());
            rMap.put("client_name",linkman.getClient().getName());
            rMap.put("name",linkman.getName());
            rMap.put("subname",linkman.getSubName());
            rMap.put("duty",linkman.getDuty());
            rMap.put("tel",linkman.getTel());
            rMap.put("mobile",linkman.getMobile());
            rMap.put("email",linkman.getEmail());
            rMap.put("birthday", DataUtil.DateToString(linkman.getBirthday(), "yyyy-MM-dd"));
            dataRows.add(JSONObject.fromObject(rMap));
        }

        long total =pager.getTotalCount();
        if(total%rows==0){
            total = total/rows;
        }else{
            if(total<rows){
                total = 1;
            }else{
                total = total/rows + 1;
            }
        }
        data.put("dataRows",dataRows);
        data.put("page",page);
        data.put("rows",rows);
        data.put("total",total);
        data.put("records",pager.getTotalCount());
        return  ajaxJson(JSONObject.fromObject(data).toString());
    }

    public void isUniqueByName() {
        PrintWriter out= null;
        try {
            out=getResponse().getWriter();
        } catch (IOException e) {
            e.printStackTrace();
        }

        if (StringUtils.isNotEmpty(keyId)){
            linkman = linkmanService.get(keyId);
            client = linkman.getClient();
        }
        else{
            if (StringUtils.isNotEmpty(clientId)){
                client = clientService.get(clientId);
            }
            else{
                out.print("true");
            }
        }

        List<Linkman> linkmanList = (List<Linkman>)linkmanService.findByPagerAndClient(new Pager(0),client).getList();
        boolean sta = false;
        for (int i =0;i<linkmanList.size();i++){
            if (linkmanList.get(i).getName().equals(newValue) && !keyId.equals(linkmanList.get(i).getId())){
                sta = true;
                break;
            }
        }
        if (sta){
            out.print("false");
        }
        else{
            out.print("true");
        }
    }

    /**
     * 上传图片
     * @return
     */
    public String uploadImg() throws IOException {
        fileManage = gridFSSave(new FileInputStream(filedata), filename, keyId,"APPLICATION/OCTET-STREAM",Linkman.class);
        fileId = fileManage.getId();
        Map<String, Object> data = new HashMap<String, Object>();
        data.put("gridId",fileId);
        data.put("fileUrl",fileManage.getUrl());
        data.put("status","200");
        data.put("title","操作状态");
        data.put("message","上传头像成功！");

        return ajaxJson(JSONObject.fromObject(data).toString());
    }

    public String show(){
        return "list";
    }

    public String read(){
        if(StringUtils.isNotEmpty(keyId)){
            linkman = linkmanService.get(keyId);
            if(StringUtils.isNoneEmpty(linkman.getFileId())){
                fileManage = fileManageService.get(linkman.getFileId());
            }

        }

        return "read";
    }

    public String input(){

        if (StringUtils.isNoneEmpty(clientId)){
            client = clientService.get(clientId);
        }
        if (StringUtils.isNotEmpty(keyId)){
            linkman = linkmanService.get(keyId);
            client = linkman.getClient();
            fileId = linkman.getFileId();
            if (StringUtils.isNotEmpty(fileId)) {
                fileManage = fileManageService.get(fileId);
            }
        }
        return  "input";
    }

    public String save(){
        if(StringUtils.isNotEmpty(keyId)){
            linkman = linkmanService.get(keyId.split(",")[0]);
            client = linkman.getClient();
        }else{
            linkman = new Linkman();
            linkman.setCreater(usersService.getLoginInfo());
        }

        if (StringUtils.isNotEmpty(clientId) && client == null){
            client = clientService.get(clientId.split(",")[0]);
        }

        if (client.equals(null)){
            return ajaxHtmlCallback("200", "保存失败，没有读取客户信息！","操作状态");
        }
        linkman.setName(name);
        linkman.setBirthday(birthday);
        linkman.setClient(client);
        linkman.setDuty(duty);
        linkman.setEmail(email);
        linkman.setIfHasDecision(ifHasDecision);
        linkman.setMobile(mobile);
        linkman.setMobile_back(mobile_back);
        linkman.setPreferences(preferences);
        linkman.setRemark(remark);
        linkman.setTel(tel);
        linkman.setRemark(remark);
        linkman.setFileId(fileId);
        linkman.setSubName(subName);
        linkman.setState(StateEnum.Enable);
        linkman.setCompany(usersService.getCompanyByUser());
        if(StringUtils.isNotEmpty(keyId)){
            linkmanService.update(linkman);
        }else{
            linkmanService.save(linkman);
        }
        return ajaxHtmlCallback("200", "保存成功！","操作状态");
    }

    public String delete(){
        if(StringUtils.isEmpty(keyId)){
            return ajaxHtmlCallback("200", "请选择联系人信息！","操作状态");
        }
        Linkman linkman = linkmanService.get(keyId);
        Map<String,Object> params = new HashMap<String,Object>();
        params.put("linkman", linkman);
        List<ProInfo> proInfoList = proInfoService.getList(params);
        if (proInfoList.size() > 0){
            return ajaxHtmlCallback("400", "当前联系人存在项目！","操作状态");
        }
        linkman.setState(StateEnum.Delete);
        linkmanService.update(linkman);
        return ajaxHtmlCallback("200", "保存成功！","操作状态");
    }


    @Override
    public Pager getPager() {
        return pager;
    }

    @Override
    public void setPager(Pager pager) {
        this.pager = pager;
    }

    @Override
    public String getKeyId() {
        return keyId;
    }

    @Override
    public void setKeyId(String lkeyId) {
        this.keyId = lkeyId;
    }

    public String getClientId() {
        return clientId;
    }

    public void setClientId(String clientId) {
        this.clientId = clientId;
    }

    public Client getClient() {
        return client;
    }

    public void setClient(Client client) {
        this.client = client;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getSubName() {
        return subName;
    }

    public void setSubName(String subName) {
        this.subName = subName;
    }

    public String getDuty() {
        return duty;
    }

    public void setDuty(String duty) {
        this.duty = duty;
    }

    public String getTel() {
        return tel;
    }

    public void setTel(String tel) {
        this.tel = tel;
    }

    public String getMobile() {
        return mobile;
    }

    public void setMobile(String mobile) {
        this.mobile = mobile;
    }

    public String getMobile_back() {
        return mobile_back;
    }

    public void setMobile_back(String mobile_back) {
        this.mobile_back = mobile_back;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getPreferences() {
        return preferences;
    }

    public void setPreferences(String preferences) {
        this.preferences = preferences;
    }

    public String getIfHasDecision() {
        return ifHasDecision;
    }

    public void setIfHasDecision(String ifHasDecision) {
        this.ifHasDecision = ifHasDecision;
    }

    public Date getBirthday() {
        return birthday;
    }

    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }

    public int getBirthdayMonth() {
        return birthdayMonth;
    }

    public void setBirthdayMonth(int birthdayMonth) {
        this.birthdayMonth = birthdayMonth;
    }

    public int getBirthdayDay() {
        return birthdayDay;
    }

    public void setBirthdayDay(int birthdayDay) {
        this.birthdayDay = birthdayDay;
    }

    public String getRemark() {
        return remark;
    }

    public void setRemark(String remark) {
        this.remark = remark;
    }

    public List<Linkman> getLinkmanList() {
        return linkmanList;
    }

    public void setLinkmanList(List<Linkman> linkmanList) {
        this.linkmanList = linkmanList;
    }

    public Linkman getLinkman() {
        return linkman;
    }

    public void setLinkman(Linkman linkman) {
        this.linkman = linkman;
    }

    public File getFiledata() {
        return filedata;
    }

    public void setFiledata(File filedata) {
        this.filedata = filedata;
    }

    public String getFilename() {
        return filename;
    }

    public void setFilename(String filename) {
        this.filename = filename;
    }

    public FileManage getFileManage() {
        return fileManage;
    }

    public void setFileManage(FileManage fileManage) {
        this.fileManage = fileManage;
    }

    public String getFileId() {
        return fileId;
    }

    public void setFileId(String fileId) {
        this.fileId = fileId;
    }

    public String getFileUrl() {
        return fileUrl;
    }

    public void setFileUrl(String fileUrl) {
        this.fileUrl = fileUrl;
    }

    public String getGridId() {
        return gridId;
    }

    public void setGridId(String gridId) {
        this.gridId = gridId;
    }
}
